package com.oldroid.apps.getit.ui;

import java.text.DecimalFormat;

import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.oldroid.apps.getit.R;
import com.oldroid.apps.getit.util.UIUtils;

public class StatusFragment extends Fragment {

	private TextView mTextView;
	private ViewGroup mRootView;
	private static final double GIGA_BYTES =  Math.pow(2, 30); // there are 2^30 bytes in 1 Gigabyte

	/**
	 * These variable store info on the available
	 * memory on the phone 
	 */
	private static Double availableSizeInGb;
	private static Double totalSizeInGb;
	private static Double usedInGb; 
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_status,
				container);

		display();

		return mRootView;

	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
	}

	@Override
	public void onDetach() {
		// TODO Auto-generated method stub
		super.onDetach();
	}

	
	
	/**
	 * Calculates the available memory on the phone
	 * and stores the results in the availableSizeInGb,
	 * totalSizeInGb, and usedInGb instance variables.
	 * 
	 */
	private void calcMemInfo(){
		
		String state = Environment.getExternalStorageState(); 
		StatFs statFs = null;
		if(state.equals(Environment.MEDIA_MOUNTED)){ //external media available
			statFs = new StatFs(Environment.getExternalStorageDirectory().getAbsolutePath());
			
		} else if (!state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)){ // no external media available
			statFs = new StatFs(Environment.getRootDirectory().getAbsolutePath()); // analzye internal phone memory instead
		}
		
		long blockSize = statFs.getBlockSize();
		long totalSize = statFs.getBlockCount() * blockSize;
		long availableSize = statFs.getAvailableBlocks() * blockSize; // only returns those blocks that are usable by applications
		long freeSize = statFs.getFreeBlocks() * blockSize; // includes every free block, including unusuable reserved blocks
		 
		 
		DecimalFormat df = new DecimalFormat("#.##"); // round to two decimal places
		availableSizeInGb = Double.parseDouble(df.format(availableSize / GIGA_BYTES));
		totalSizeInGb = Double.parseDouble(df.format(totalSize / GIGA_BYTES));
		usedInGb = totalSizeInGb - availableSizeInGb;
		
	}
	
	
	/**
	 * Returns information regarding the available memory
	 * on the phone. If an SD card is present, that information is returned.
	 * If an SD card is not present, then the phone internal memory information
	 * is returned.
	 * @return
	 */
	private String getMemInfo(){
		
		calcMemInfo(); // calculate the available memory
		
		String output = "";
		
		output += String.format("Used Mem : %.2f GB.", usedInGb);
		output += String.format("Available Mem : %.2f GB.\n", availableSizeInGb);
		
		return output;
	}
	
	/**
	 * Loads the Pie Chart showing the information on the available
	 * memory on the phone
	 */
	private void showPieChart(){
	
		if(!isLoaded()){
			calcMemInfo(); 
		}
		
		
		/*
		 * Create the pie chart
		 * 
		 */
		
		double [] values = new double [] {availableSizeInGb, usedInGb}; 
		int [] colors = new int[] {Color.GREEN, Color.BLUE };
		DefaultRenderer renderer = ChartUtils.buildCategoryRenderer(colors);
		renderer.setZoomButtonsVisible(true);
		renderer.setZoomEnabled(true);
		renderer.setChartTitleTextSize(20);
		
		// Make the category series
		CategorySeries series = new CategorySeries("SD Card");
		int k = 0;
		series.add(String.format("Used Memory (%.2f GB)", usedInGb), usedInGb);
		series.add(String.format("Available Memory (%.2f GB)", availableSizeInGb), availableSizeInGb);
		
		
		Intent i =  ChartFactory.getPieChartIntent(getActivity().getApplicationContext(),series,renderer,"SD Card" );
		getActivity().startActivity(i);
		
	}
	
	/**
	 * Checks if the available memory on the phone has already
	 * been caclulated in the past (by a call to calcMemInfo). 
	 * @return 
	 */
	private boolean isLoaded(){
		if(availableSizeInGb == null || totalSizeInGb == null || usedInGb == null ){
			return false;
		} else {
			return true;
		}
		
	}
	
	private void display() {

		mRootView.removeAllViews();
		// Status Summary
		View helper = getActivity().getLayoutInflater().inflate(
							R.layout.status_item, mRootView, true);
		
		TextView tv = (TextView) helper.findViewById(R.id.status_text_info);
		
		
		tv.setText(getMemInfo());
		
		/**
		 * 
		 */
		
		// Kinda Dashboard(Display the detail part with the graph)
		/*
		 * mRootView.setOnClickListener(new View.OnClickListener() { public void
		 * onClick(View view) { startActivity(new Intent(getActivity(),
		 * DownloadsActivity.class));
		 * 
		 * }
		 * 
		 * });.
		 */

		if (!UIUtils.isHoneycombTablet(getActivity())) {
			View separator = new View(getActivity());
			separator.setLayoutParams(new ViewGroup.LayoutParams(1,
					ViewGroup.LayoutParams.FILL_PARENT));
			separator.setBackgroundResource(R.drawable.status_separator);
			mRootView.addView(separator);

			View view = getActivity().getLayoutInflater().inflate(
					R.layout.status_detail, mRootView, false);

			StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
					.getPath());
			double sdAvailSize = (double) stat.getAvailableBlocks()
					* (double) stat.getBlockSize();
			// One binary gigabyte equals 1,073,741,824 bytes.
			double gigaAvailable = sdAvailSize / 1073741824;

			// HomeActivity.details.setText("" + gigaAvailable); // causes app
			// to crash on launch.

			view.setOnClickListener(new View.OnClickListener() {

				public void onClick(View arg0) {
					//startActivity(new Intent(getActivity(),
					//		StatusActivity.class));
					
					showPieChart(); // load the pie chart.
					

				}
			});
			mRootView.addView(view);
		}

	}
	
	
	

}
